package leetcode.dfs;
//695. 岛屿的最大面积  DFS/BFS
public class MaxAreaOfIsland {
    public int maxAreaOfIsland(int[][] grid) {

        int maxLength=0;
        for (int i = 0; i < grid.length; i++) {
            for (int j =0;j<grid[0].length;j++){
                maxLength=Math.max(maxLength,dfs(grid,i,j));
            }
        }
        return maxLength;
    }

    private int dfs(int[][] grid, int x, int y) {
        if (x<0 || x>=grid.length || y<0 ||y>=grid[0].length ||
              //不是土地
                grid[x][y]==0
        ){
        return 0;
        }
        grid[x][y]=0; //沉岛，避免重复遍历
        int length=1;
         int[] dx={-1,0,0,1};
         int[] dy={0,1,-1,0};
         for (int i =0;i<4;i++){
             int mx=dx[i]+x;
             int my=dy[i]+y;
             length+=dfs(grid,mx,my);
         }  
         return length;
    }
}
